// 事件总线
const bus = new EventBus();
const { Scene, Sprite, Group, Label } = spritejs;
const container = document.getElementById('stage');
const btn = document.getElementById('btn');
const btn1 = document.getElementById('btn1');
const btn3 = document.getElementById('btn3');
const btn4 = document.getElementById('btn4');
const girdType = document.getElementById('girdType');
const file = document.getElementById("file");
const imgUrl = 'https://p4.ssl.qhimg.com/t01423053c4cb748581.jpg';
const imgCC = document.querySelector('img');
const url_in = document.getElementById("url_in");
const app = document.querySelector("#app");
const dialog = document.querySelector(".dialog_box");
const mask = document.querySelector(".mask");
const close = document.querySelector(".close");
const slider = document.querySelector(".slider");
const slider_btn = document.querySelector(".slider_btn");
const slider_icon = document.querySelector(".slider_icon");
// 阻止右键默认行为
container.oncontextmenu = function (event) {
    event.returnValue = false;
    return false;
}
// 执行环境
let environment = '';
// 判断浏览器执行环境
if (__browser__.versions.mobile || __browser__.versions.ios || __browser__.versions.android ||
    __browser__.versions.iPhone || __browser__.versions.iPad) {
    environment = 'mobile';
} else {
    environment = 'PC';
}

window.alert("建议您使用全屏模式....,如需使用全屏模式请在菜单中点击全屏按钮");


window.onload = function () {
    if (navigator.geolocation) {

        var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };
        console.log(navigator.geolocation);
        // console.log(navigator.geolocation.getCurrentPosition());
        let id = navigator.geolocation.watchPosition(function (position) {
            console.log(position);
            console.log("纬度" + position.coords.latitude + "经度" + position.coords.longitude)
        }, function (err) {
            switch (err.code) {
                case err.PERMISSION_DENIED: return "PERMISSION_DENIED";
                case err.POSITION_UNAVAILABLE: return "POSITION_UNAVAILABLE";
                case err.TIMEOUT: return "TIMEOUT";
                default: return "UNKNOWN_ERROR";
            }
        }, options)
    } else {
        console.log("你的浏览器不支持geolocation");
    }
}
window.onresize = resize;
resize();
async function resize() {
    // 移除先前的元素
    container.innerHTML = '';
    // 默认图片
    url_in.value = imgUrl;

    // 自适应宽高---强制横屏
    const width = document.documentElement.clientWidth;
    const height = document.documentElement.clientHeight;
    if (width < height) {
        dialog.style.height = width + 'px';
        dialog.style.width = height + 'px';
        dialog.style.transform = 'rotate(-90deg)';
        dialog.style.transformOrigin = '50% 50%';
        dialog.style.top = (height - width) / 2 + 'px';
        dialog.style.left = 0 - (height - width) / 2 + 'px';
        menuEvent('shu');
    } else {
        dialog.style.width = width + 'px';
        dialog.style.height = height + 'px';
        dialog.style.transform = 'rotate(0)';
        dialog.style.top = 0;
        dialog.style.left = 0;
        menuEvent('heng');
    }
    // 菜单按钮触发事件(自适应,触摸事件)
    function menuEvent(type) {
        let x = 0, y = 0, l = 0, t = 0;
        if (type === 'shu') {
            slider.style.top = height - slider.offsetHeight + 'px';
            slider.style.left = width / 2 - slider.offsetWidth / 2 + 'px';
            slider.style.transform = 'rotate(-90deg)';
            slider.style.transformOrigin = '15px 15px';
            slider.addEventListener('touchstart', e => {
                x = e.targetTouches[0].clientX;
                l = slider.offsetLeft;
                function move(e) {
                    if (e.targetTouches[0].clientX - (x - l) <= 0) {
                        slider.style.left = 0;
                    } else if (e.targetTouches[0].clientX - (x - l) + slider.offsetWidth >= width) {
                        slider.style.left = width - slider.offsetWidth + 'px';
                    } else {
                        slider.style.left = e.targetTouches[0].clientX - (x - l) + 'px';
                    }
                };
                function end() {
                    window.removeEventListener('touchmove', move);
                    window.removeEventListener('touchend', end);
                };
                window.addEventListener('touchmove', move);
                window.addEventListener('touchend', end);
            }, false)
        } else if (type === 'heng') {
            slider.style.top = height / 2 - slider.offsetHeight / 2 + 'px';
            slider.style.left = 0;
            slider.style.transform = 'rotate(0)';
            slider.addEventListener('touchstart', e => {
                y = e.targetTouches[0].clientY;
                t = slider.offsetTop;
                function move(e) {
                    if (e.targetTouches[0].clientY - (y - t) <= 0) {
                        slider.style.top = 0;
                    } else if (e.targetTouches[0].clientY - (y - t) + slider.offsetHeight >= height) {
                        slider.style.top = height - slider.offsetWidth + 'px';
                    } else {
                        slider.style.top = e.targetTouches[0].clientY - (y - t) + 'px';
                    }
                };
                function end() {
                    window.removeEventListener('touchmove', move);
                    window.removeEventListener('touchend', end);
                };
                window.addEventListener('touchmove', move);
                window.addEventListener('touchend', end);
            }, false)
        }

    }

    // 获取外层元素宽高,让画布等于外层宽高
    const container_W = app.offsetWidth;
    const container_H = app.offsetHeight;

    const W = container_W, H = container_H;     // 图片固定宽高
    // 大容器，canvas本身
    const scene = new Scene({
        container,
        width: W,
        height: H,
    });
    const layer = scene.layer();

    // 确定按钮
    btn4.onclick = async function () {
        const imgSrc = await loadHttpImg();
        main(imgSrc);
    }
    btn4.click();
    // 选择文件加载
    file.onchange = function () {
        let Reader = new FileReader();		 // 创建文件读取对象 
        Reader.readAsDataURL(this.files[0]); //读取Blob，获取DataURL 
        Reader.onloadend = function () {
            let img = new Image();
            img.src = Reader.result;
            img.onload = function () {
                main(img)
            }
        }
    }
    let handlerSlider = false;
    slider_icon.onclick = function () {
        handlerSlider = !handlerSlider;
        if (handlerSlider) {
            slider.style.width = '100px';
        } else {
            slider.style.width = '30px';
        }

    };
    slider_btn.onclick = function () {
        dialog.style.display = 'block';
        slider.style.width = '30px';
        handlerSlider = false;
    };
    mask.onclick = function () {
        dialog.style.display = 'none';
        slider.style.width = '30px';
        handlerSlider = false;
    };
    close.onclick = function () {
        dialog.style.display = 'none';
        slider.style.width = '30px';
        handlerSlider = false;
    };

    // 加载网络图片
    function loadHttpImg() {
        return new Promise((res, rej) => {
            // 默认用 imgUrl 的地址
            let URL = url_in.value;
            // 发起AJAX请求
            let ajax = new XMLHttpRequest();
            ajax.open('GET', URL, true);
            ajax.responseType = "blob";     //以流的形式接收
            ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            ajax.onload = function () {
                if (this.status == 200) {
                    let blob = this.response;
                    let oReader = new FileReader();
                    oReader.readAsDataURL(blob);
                    oReader.onloadend = function (e) {
                        let img = new Image();
                        img.src = oReader.result;
                        img.onload = function () {
                            res(this)
                        }
                    }
                }
            }
            ajax.send();
        })
    }
    // 加载本地图片
    function loadLocalImg() {
        return new Promise((res, rej) => {
            document.querySelector("#file").onchange = function () {
                let Reader = new FileReader();		 // 创建文件读取对象 
                Reader.readAsDataURL(this.files[0]); //读取Blob，获取DataURL 
                Reader.onloadend = function () {
                    res(Reader.result)
                }
            }
        })
    }

    // 主程序
    function main(imgSrc) {
        layer.removeAllChildren();
        // 步数
        let THEY_COUNT = 0;
        // 示例图片
        let imgW = imgSrc.width;
        let imgH = imgSrc.height;
        let size = [W, H], rotate = 0;
        if (width < height) {
            if (imgW > imgH) {
                size = [H, W];
                rotate = -90;
            }
        } else {
            if (imgW < imgH) {
                size = [H, W];
                rotate = -90;
            }
        }

        // 背景图
        const c = new Sprite({
            anchor: [0.5, 0.5],
            pos: [W / 2, H / 2],
            size,
            texture: imgSrc,
            rotate
        })
        layer.append(c);

        // 快照，将图片处理后放在canvas中，再取出其数据，方便做拼图处理
        const canvas = scene.snapshot();
        const isimg = new Image();
        isimg.src = canvas.toDataURL();

        // 分组容器
        const group = new Group();
        group.attr({
            size: [W, H],
            pos: [0, 0],
            // bgcolor: 'white',
            fillColor: `rgb(255, 0, 0)`
        })
        layer.append(group);
        c.remove(); // 移除元素

        // 开始切图 ( 将每个元素的数据备份在一个集合中，方便后面对拼图结果做检测 )
        // 格子数据集合
        let data = {};
        data.index = 0; // 索引
        data.list = []; // 数据  

        // 开始拼图
        btn.onclick = function () {
            bus.off();
            cutImg();
            // Math.floor(Math.random()*(10-6))+6 范围内随机抽取数值
            let posArr = group.children.map(item => {
                return item.getAttribute('pos')
            })
            group.children.forEach(item => {
                // 随机抽取一张图片的位置
                let arr = posArr.splice(Math.floor(Math.random() * (posArr.length)), 1);
                // 原始位置
                let oldArr = item.getAttribute('pos');
                item.animate([
                    { pos: oldArr },
                    { pos: arr[0] }
                ], {
                    duration: 200,
                    fill: 'forwards'
                })
            });
            pintu();    // 开始游戏！！！
            // btn.onclick = null;
        }
        btn.click();
        // 开始校验
        btn1.onclick = function () {
            // 结果 true 不通过， false 为通过
            let result = data.list.some(item => {
                return (group.getElementById(item.id).getAttribute('x') !== item.x || group.getElementById(item.id).getAttribute('y') !== item.y)
            })
            result ? alert("噫噫噫，你还没拼对，不要急！") : alert("太棒啦！你已经成功拼成了一张美图，庆祝一下吧~~~")
        }
        // 重置
        btn3.onclick = function () {
            bus.off();  // 清空事件车
            group.children.forEach(item => {
                item.animate([
                    { pos: item.getAttribute('pos') },
                    { pos: [0, 0] }
                ], {
                    duration: 200,
                    fill: 'forwards'
                })
            })
            setTimeout(() => {
                group.removeAllChildren();
            }, 200)
        }
        // 拼图函数
        function pintu() {
            let x = 0, y = 0;  //鼠标按下时相对当前元素的坐标
            let offsetx = 0, offsety = 0;   //鼠标按下时相对group的坐标
            let disx = 0, disy = 0;   //元素初始化坐标
            let x2 = 0, y2 = 0;     //鼠标移动时坐标相对鼠标按下时坐标的偏移差
            let dir = '';   //移动方向
            let _id = '';   //元素ID
            group.children.forEach(item => {
                // PC端跟移动端分开处理事件
                if (environment == 'mobile') {
                    item.addEventListener("touchstart", down.bind(item));
                }
                else {
                    item.addEventListener("mousedown",down.bind(item));
                }

            })
            // 鼠标按下事件
            function down(e){
                // 判断鼠标左键事件才执行
                if(e.originalEvent.button){
                    if (e.originalEvent.button !== 0) return
                }
                dir = "";
                x = e.x - this.getAttribute('x');
                y = e.y - this.getAttribute('y');
                offsetx = e.x;
                offsety = e.y;
                _id = this.id;
                disx = this.getAttribute('x');
                disy = this.getAttribute('y');
                this.flag = true;
                // document.querySelector('body').style.cursor = "move";
                // this.setAttribute("border", [1, 'green']);
                if(environment == 'mobile'){
                    group.addEventListener("touchmove", move);
                    group.addEventListener("touchend", mouseup);
                }else{
                    group.addEventListener("mousemove", move);
                    group.addEventListener("mouseup", mouseup);
                }
                
            }
            // 鼠标移动事件
            function move(e) {
                const _this = group.getElementById(_id);

                if (!_this.flag) return;
                let x1, y1;
                x1 = e.x - x;
                y1 = e.y - y;
                x2 = e.x - offsetx;
                y2 = e.y - offsety;

                let w = _this.getAttribute("width");
                let h = _this.getAttribute("height");
                _this.setAttribute('zIndex', 11);
                // 控制横向纵向移动，每次只能往一个方向移动，并且只能移动一格位置
                if (dir === '') {
                    if (Math.abs(x2) >= 15) {
                        dir = 'x'
                    } else if (Math.abs(y2) >= 15) {
                        dir = 'y'
                    }
                } else {
                    if (dir === 'x') {
                        // 往右移动
                        if (x2 > 0 && x2 >= w) {
                            _this.setAttribute('x', disx + w);
                            // 往左移动
                        } else if (x2 < 0 && Math.abs(x2) >= w) {
                            _this.setAttribute('x', disx - w);
                        } else {
                            _this.setAttribute('x', x1)
                        }
                    } else {
                        // 往下移动
                        if (y2 > 0 && y2 >= h) {
                            _this.setAttribute('y', disy + h);
                            // 往上移动
                        } else if (y2 < 0 && Math.abs(y2) >= h) {
                            _this.setAttribute('y', disy - h);
                        } else {
                            _this.setAttribute('y', y1)
                        }
                    }
                }
            }
            // 鼠标抬起事件
            function mouseup() {
                const _this = group.getElementById(_id);
                let w = _this.getAttribute("width");
                let h = _this.getAttribute("height");
                /**
                    @param (x2 > 0 && x2 >= w / 2)            偏移位大于元素宽度的一半
                    @param (x2 < 0 && Math.abs(x2) >= w)      偏移位小于元素宽度的一半
                    @param (y2 > 0 && y2 >= h / 2)            偏移位大于元素高度的一半
                    @param (y2 < 0 && Math.abs(y2) >= h / 2)  偏移位小于元素高度的一半
                    @param (disx + w != W)                    最右边缘元素
                    @param (disx != 0)                        最左边缘元素
                    @param (disy + h != H)                    最下边缘元素
                    @param (disy != 0)                         最上边缘元素
                */
                // 格子自动归位识别
                if (dir === 'x') {
                    // 往右移动
                    if (x2 > 0 && x2 >= w / 2 && disx + w != W) {
                        _this.setAttribute('x', (disx + w));
                        // 往左移动
                    } else if (x2 < 0 && Math.abs(x2) >= w / 2 && disx != 0) {
                        _this.setAttribute('x', (disx - w));
                    } else {
                        _this.setAttribute('x', disx);
                    }
                } else if (dir === 'y') {
                    console.log( disy + h,"y");
                    console.log(H,"H");
                    // 往下移动
                    if (y2 > 0 && y2 >= h / 2 && disy + h != H && disy + h != H - 1) {
                        _this.setAttribute('y', disy + h);
                        // 往上移动
                    } else if (y2 < 0 && Math.abs(y2) >= h / 2 && disy != 0) {
                        _this.setAttribute('y', disy - h);
                    } else {
                        _this.setAttribute('y', disy);
                    }
                }
                // 横向/纵向坐标发生变化时
                if (_this.getAttribute("x") != disx || _this.getAttribute("y") != disy) {
                    let currentPos = _this.getAttribute("pos");
                    let beforePos = [disx, disy];
                    bus.emit("up", beforePos, currentPos, _id);     // 派发事件车

                }

                _this.flag = false;
                _this.setAttribute('zIndex', 0);

                if (environment == 'mobile') {
                    group.removeEventListener("touchmove", move);
                    group.removeEventListener("touchend", mouseup);
                } else {
                    console.log(123);
                    group.removeEventListener("mousemove", move);
                    group.removeEventListener("mouseup", mouseup);

                }
                _this.setAttribute("border", [0, 'red'])
                document.querySelector('body').style.cursor = "default";

                // 重置必要变量/参数 ------ ( 不必要 )
                x = 0, y = 0;  //鼠标按下时相对当前元素的坐标
                offsetx = 0, offsety = 0;   //鼠标按下时相对group的坐标
                disx = 0, disy = 0;   //元素初始化坐标
                x2 = 0, y2 = 0;     //鼠标移动时坐标相对鼠标按下时坐标的偏移差
                dir = '';   //移动方向
            }

            // 鼠标抬起事件处理回调
            bus.on("up", (beforePos, currentPos, id) => {
                let _id__ = findIndex(currentPos, group.children, id);
                group.getElementById(_id__).animate([
                    { pos: group.getElementById(_id__).getAttribute('pos') },
                    { pos: beforePos }
                ], {
                    duration: 200,
                    fill: 'forwards'
                });
                // 更新步数
                THEY_COUNT++;
                layer.getElementById('count').setAttribute("text", `当前步数：${THEY_COUNT}`)
                setTimeout(() => {
                    auto_detection();  // 自动检测
                }, 400);
                // group.getElementById(_id__).setAttribute('pos', beforePos);
            })
            // 找到元素在group容器中的索引
            function findIndex(arr, array, id) {
                let o = 0;
                array.forEach((item, i) => {
                    if (id != item.id && parseInt(item.getAttribute('x')) == parseInt(arr[0]) && parseInt(item.getAttribute('y')) == parseInt(arr[1])) {
                        o = item.id;
                    }
                })
                return o;
            }
            // 自动检测函数
            function auto_detection() {
                // 结果 true 不通过， false 为通过
                console.log(data);
                let result = data.list.some(item => {
                    return (group.getElementById(item.id).getAttribute('x') !== item.x || group.getElementById(item.id).getAttribute('y') !== item.y)
                })
                console.log(result);
                if (result == false) {
                    window.alert("太棒啦！你已经成功拼成了一张美图，庆祝一下吧~~~");
                    // 移除子元素事件
                    // group.children.forEach(item=>{
                    //     item.removeEventListener("touchstart",down);
                    //     item.removeEventListener("mousedown",down);
                    // })
                }
            }
        }
        // 切图
        function cutImg() {
            group.removeAllChildren();
            data.index = 0; // 索引
            data.list = []; // 数据
            let framentList = [];
            // 横向纵向切图等份 X Y
            const [X, Y] = girdType.options[girdType.selectedIndex].value.split(",");
            // J 排在前面横向顺序切图, I 排在前面纵向切图顺序
            for (let i = 0; i < X; i++) {
                for (let j = 0; j < Y; j++) {
                    const b = new Sprite({
                        size: [parseInt(W / X), parseInt(H / Y)],
                        x: i * parseInt(W / X),
                        y: j * parseInt(H / Y),
                        texture: isimg.src,
                        sourceRect: [i * parseInt((W / X)), j * parseInt((H / Y)), parseInt(W / X), parseInt(H / Y)]
                    })
                    // 将每个格子的数据储存起来
                    data.index++;
                    b.id = "abc_" + data.index;
                    b.className = "abc_" + data.index;
                    b.flag = false;
                    let obj = {
                        id: b.id,
                        pos: b.getAttribute('pos'),
                        x: b.getAttribute('x'),
                        y: b.getAttribute('y'),
                        w: b.getAttribute('width'),
                        h: b.getAttribute('height'),
                        size: b.getAttribute('size')
                    };
                    data.list.push(obj);
                    framentList.push(b);
                }
            }
            // 一次性塞进容器中
            group.append(...framentList);
            // 将碎片集合清空
            setTimeout(()=>{
                framentList = null;
            },100)
            // 步数显示
            const text1 = new Label('当前步数：0');
            text1.attr({
                pos: [10, 10],
                fillColor: 'black',
                font: 'oblique small-caps bold 14px Arial',
                id: 'count',
                pointerEvents: 'none',
                index: 9999
            });
            layer.append(text1);

        }
    }

};